var express = require('express');
var fs = require('fs')
var path = require('path')
var BusBoy = require('busboy');
var router = express.Router();
var db = require('../config/db.config');

/* GET users listing. */
router.get('/all', (req, res) => {
  db.query('SELECT * from users', (err, data) => {
    if (err) {
      res.send({ code: 0, msg: "error", data: [] })
    } else {
      res.send({ code: 200, msg: "success", data })
    }
  })
})
/**
 * 头像上传
 */
router.post('/upload', (req, res) => {
  const bb = BusBoy({ headers: req.headers })
  let img = {
    filename: '',//图片名称
    encoding: '',//图片大小
    mimeType: '',//图片类型
    imgUrl: '',//图片地址
  }
  bb.on('file', (name, file, info) => {
    console.log(info)
    const { filename, encoding, mimeType } = info
    const filePath = new Date().getTime() + path.extname(filename)
    img = { ...info, filename: filePath }
    const saveTo = path.join(__dirname, '../uploads', filePath)
    file.pipe(fs.createWriteStream(saveTo))
  })
  bb.on('finish', () => {
    img.imgUrl = "http://localhost:3000/uploads/" + img.filename
    const avatar = img.imgUrl
    // const id = req.query.id
    // console.log(id)
    db.query(`update users set avatar = '${avatar}' where id = '1'`, (err, data) => {
      if (err) {
        res.send({ code: 0, msg: "error", data: [] })
      } else {
        data = {
          code: 200,
          msg: '上传成功',
          data: img
        }
        res.send({ code: 200, msg: "success", data })
      }
    })
  })
  return req.pipe(bb)
})

module.exports = router;
